package com.sx.shop.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sx.shop.entity.User;
import com.sx.shop.mapper.UserMapper;
import com.sx.shop.util.MD5Util;
import com.sx.shop.vo.ResultVo;





@Service
public class UserService {
	//依赖注入
	@Autowired
	private UserMapper userMapper;
	
	public ResultVo selectUser( String keyword, Integer page , Integer limit) {
		ResultVo vo = new ResultVo();
		
		PageHelper.startPage( page , limit);//代码下的第一个查询，有分页效果		
		List<User> list = userMapper.selectUser(keyword);	
		PageInfo<User> pageInfo = new PageInfo<>(list);
		vo.setData(list);
		vo.setCount(pageInfo.getTotal());	
		return vo;
	}
	
	public void doSave(User user) {
		// TODO Auto-generated method stub
		if(user.getId() == null) {//是新增
			user.setPassword(MD5Util.md5(user.getPassword()));
			userMapper.insert(user);
		}else {
			userMapper.update(user);
		}
		
	}

	public void doDel(Integer userId) {
		// TODO Auto-generated method stub
		userMapper.delete(userId);
	}

	public User selectUserById(Integer id) {
		// TODO Auto-generated method stub
		return userMapper.selectUserById(id);
	}

	public boolean check(String useranme, String password,HttpSession session) {
		// TODO Auto-generated method stub
		
		User user=userMapper.selectUserByUsername(useranme);
			
		//System.out.println(user.getName()+"   "+user.getPassword());
		
		boolean b= user!=null &&user.getPassword().equals(MD5Util.md5(password));
		if(b) {
			session.setAttribute("current", user);
		}
		return b;
			
	}
	public User findByUserName(String userName)
	{
		return userMapper.selectUserByUsername(userName);
	}
	public int register(String username,String password,String salt,Integer sex,String role,String name)
	{
		if(userMapper.selectUserByUsername(username)==null)
		{
			User user=new User();
			user.setPassword(password);
			user.setRole(role);
			user.setSalt(salt);
			user.setUsername(username);
			user.setSex(sex);
			user.setName(name);
			return userMapper.add(user);
		}
		return 0;
	}
}
